package com.xyz.jira.plugin;

import com.atlassian.jira.ComponentManager;
import com.atlassian.jira.project.Project;
import com.atlassian.plugins.rest.common.security.AnonymousAllowed;
import com.xyz.jira.plugin.responses.IssueTypesInfo;
import com.xyz.jira.plugin.responses.ProjectInfo;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

/**
 * A resource of message.
 */
@Path("/projectInfo")
public class ProjectDetails {

	/**
	 * Gets a listing of issue types available for a project.
	 * 
	 * @param pid
	 *            Project id for which to get the issue types
	 * @return the message from the key parameter or the default message
	 */
	@GET
	@AnonymousAllowed
	@Produces({ MediaType.APPLICATION_JSON })
	public Response getIssueTypes(@QueryParam("pid") String pid) {
		long projectId = -1;

		if (pid != null && pid.length() > 0) {
			// Load the project by id
			Project project;
			try {
				projectId = Long.parseLong(pid);
				project = ComponentManager.getInstance().getProjectManager()
						.getProjectObj(projectId);

			} catch (NumberFormatException nfe) {
				// Ignore number format error
				// Try loading the project by key
				project = ComponentManager.getInstance().getProjectManager()
						.getProjectObjByKey(pid.toUpperCase());
			}
			if (project != null) {
				return Response.ok(
						new ProjectInfo(project.getId() + "", project.getKey(),
								project.getName())).build();
			} else {
				return Response.ok(
						new ProjectInfo("No project found with given id/key", null, null)).build();
			}
		} else {
			return Response.ok(new ProjectInfo("No pid provided", null, null))
					.build();
		}
	}
}